package com.zixuan.gulicollege.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zixuan.gulicollege.common_utils.PageUtils;
import com.zixuan.gulicollege.common_utils.ResultCode;
import com.zixuan.gulicollege.eduservice.config.EduConstant;
import com.zixuan.gulicollege.eduservice.mapper.EduCourseMapper;
import com.zixuan.gulicollege.eduservice.service.EduChapterService;
import com.zixuan.gulicollege.eduservice.service.EduCourseDescriptionService;
import com.zixuan.gulicollege.eduservice.service.EduCourseService;
import com.zixuan.gulicollege.eduservice.service.EduVideoService;
import com.zixuan.gulicollege.entity.eduservice.EduCourse;
import com.zixuan.gulicollege.entity.eduservice.EduCourseDescription;
import com.zixuan.gulicollege.entity.eduservice.vo.CourseFrontVO;
import com.zixuan.gulicollege.entity.eduservice.vo.CourseInfoVO;
import com.zixuan.gulicollege.entity.eduservice.vo.CourseInitFrontVO;
import com.zixuan.gulicollege.entity.eduservice.vo.CoursePublishVO;
import com.zixuan.gulicollege.exception_handler.ConstantExceptionInfo;
import com.zixuan.gulicollege.exception_handler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zixuan
 * @since 2021-05-08
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService descriptionService;

    @Autowired
    private EduCourseService courseService;

    @Autowired
    private EduVideoService videoService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private EduCourseMapper courseMapper;

    @Override
    public String saveCourseInfo(CourseInfoVO courseInfoVO) {
        // 课程表添加基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        int row = baseMapper.insert(eduCourse);

        if (row <= 0) {
            throw new GuliException(ResultCode.ERROR, ConstantExceptionInfo.FAIL_ADD_COURSE);
        }

        // 获取添加之后的id
        String cid = eduCourse.getId();

        // 向课程简介表添加课程信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVO.getDescription());
        // 课程表id与简介表id相同
        courseDescription.setId(cid);
        descriptionService.save(courseDescription);
        return cid;
    }

    @Override
    public CourseInfoVO getCourseInfo(String courseId) {

        // 查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVO courseInfoVO = new CourseInfoVO();
        BeanUtils.copyProperties(eduCourse, courseInfoVO);

        // 查询描述表
        EduCourseDescription courseDescription = descriptionService.getById(courseId);
        courseInfoVO.setDescription(courseDescription.getDescription());

        return courseInfoVO;
    }

    @Override
    public int updateCourseInfo(CourseInfoVO courseInfoVO) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        int row = baseMapper.updateById(eduCourse);

        if (row <= 0) {
            throw new GuliException(ResultCode.ERROR, ConstantExceptionInfo.FAIL_UPDATE_COURSE);
        }


        EduCourseDescription courseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVO, courseDescription);
        QueryWrapper<EduCourseDescription> wrapperCourseDescription = new QueryWrapper<>();
        descriptionService.updateById(courseDescription);

        return row;
    }

    @Override
    public CoursePublishVO publishCourseInfo(String id) {
        return baseMapper.getPublishCourseInfo(id);
    }

    @Override
    public Map<String, Object> pageListCourse(Integer current, Integer limit) {
        Page<EduCourse> pageCourse = new Page<>(current, limit);

        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();

        // 按照降序排列
        wrapper.orderByDesc("gmt_create");

        return PageUtils.pageInfo(pageCourse, wrapper, courseService);
    }

    @Override
    public Map<String, Object> pageCourseCondition(Integer current, Integer limit, CoursePublishVO coursePublishVO) {

        Page<EduCourse> coursePage = new Page<>(current, limit);

        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();

        String courseTitle = coursePublishVO.getCourseTitle();
        String status = coursePublishVO.getStatus();
        String begin = coursePublishVO.getBegin();
        String end = coursePublishVO.getEnd();

        if (!StringUtils.isEmpty(courseTitle)) {
            // 模糊查询
            wrapper.like("title", courseTitle);
        }

        if (!StringUtils.isEmpty(status)) {
            // 等于
            wrapper.eq("status", status);
        }

        if (!StringUtils.isEmpty(begin)) {
            // 大于
            wrapper.ge("gmt_create", begin);
        }

        if (!StringUtils.isEmpty(end)) {
            // 小于
            wrapper.le("gmt_create", end);
        }

        wrapper.orderByDesc("gmt_create");

        return PageUtils.pageInfo(coursePage, wrapper, courseService);
    }

    @Override
    public void removeCourse(String id) {
        // 根据课程id删除小结
        videoService.removeVideoByCourseId(id);

        // 根据课程id删除章节
        chapterService.removeChapterByCourseId(id);

        // 根据课程id删除描述信息
        descriptionService.removeById(id);

        // 根据课程id删除课程本身
        int row = baseMapper.deleteById(id);
        if (row <= 0) {
            throw new GuliException(ResultCode.ERROR, ConstantExceptionInfo.FAIL_DELETE_COURSE);
        }

    }

    @Cacheable(key = "'getCourseList'", value = "course")
    @Override
    public List<EduCourse> getCourseList() {
        // 查询前8条热门课程
        QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<>();
        courseWrapper.orderByDesc("view_count");
        courseWrapper.last("limit 8");
        courseWrapper.eq("status", EduConstant.COURSE_STATUS_NORMAL);
        List<EduCourse> list = courseService.list(courseWrapper);
        for (EduCourse eduCourse : list) {
            redisTemplate.opsForValue().set(eduCourse.getId() + "view_count", eduCourse.getViewCount().toString());
            redisTemplate.opsForValue().set(eduCourse.getId() + "buy_count", eduCourse.getBuyCount().toString());
        }
        return courseService.list(courseWrapper);
    }

    @Override
    public List<EduCourse> getTeacherCourseById(String id) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("teacher_id", id);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public CourseInitFrontVO getCourseFrontById(String id) {
        return baseMapper.getCourseFrontById(id);
    }

    @Override
    public Map<String, Object> getCourseFrontList(Integer current, Integer limit, CourseFrontVO courseFrontVO) {

        Page<EduCourse> coursePage = new Page<>(current, limit);

        QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<>();

        // 先判断当前课程是否发布
        courseWrapper.eq("status", EduConstant.COURSE_STATUS_NORMAL);

        // 判断VO对象是否为空
        if (courseFrontVO == null) {
            // 默认按照时间进行排序
            courseWrapper.orderByDesc("gmt_create");
            return PageUtils.pageInfo(coursePage, courseWrapper, courseService);
        }

        String subjectParentId = courseFrontVO.getSubjectParentId();
        String subjectId = courseFrontVO.getSubjectId();
        String buyCountSort = courseFrontVO.getBuyCountSort();
        String priceSort = courseFrontVO.getPriceSort();

        // 查看是否根据课程名称查询分页
        if (!StringUtils.isEmpty(subjectParentId)) {
            courseWrapper.eq("subject_parent_id", subjectParentId);
        }

        // 查看是否根据课程分类查询分页
        if (!StringUtils.isEmpty(subjectId)) {
            courseWrapper.eq("subject_id", subjectId);
        }

        // 是否根据购买数量排序
        if (!StringUtils.isEmpty(buyCountSort)) {
            courseWrapper.orderByDesc("buy_count");
        }

        // 课程是否免费
        if (!StringUtils.isEmpty(priceSort)) {
            courseWrapper.le("price", priceSort);
        }

        if (StringUtils.isEmpty(buyCountSort) && StringUtils.isEmpty(priceSort)) {
            // 默认按照时间进行排序
            courseWrapper.orderByDesc("gmt_create");
        }

        return PageUtils.pageInfo(coursePage, courseWrapper, courseService);
    }

    @Override
    public List<EduCourse> getCourseFrontBySubjectId(String id) {
        QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<>();
        courseWrapper.eq("subject_id", id);
        courseWrapper.eq("status", EduConstant.COURSE_STATUS_NORMAL);
        return baseMapper.selectList(courseWrapper);
    }

    @Override
    public CourseInitFrontVO getCourseInfoById(String id) {
        CourseInitFrontVO courseInfo = courseMapper.getCourseFrontById(id);
        String buyCount = redisTemplate.opsForValue().get(id + "buy_count");
        String viewCount = redisTemplate.opsForValue().get(id + "view_count");

        if (buyCount != null && viewCount != null) {
            courseInfo.setBuyCount(Long.valueOf(buyCount));
            courseInfo.setViewCount(Long.valueOf(viewCount));
        }
        if (courseInfo != null) {
            redisTemplate.opsForValue().set(id + "view_count", courseInfo.getViewCount().toString());
            redisTemplate.opsForValue().set(id + "buy_count", courseInfo.getBuyCount().toString());
        }
        return courseInfo;
    }
}
